package com.tencent.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.tencent.common.Configure;
import com.tencent.common.Util;

/**
 * 获取微信用户信息
 * @author 唐乾红
 * @修改日期 2016-08-02 10:00:00
 */
public class WxAccessTokenService {
	private static final Log logger = LogFactory.getLog(WxAccessTokenService.class);

	/**
	 * access_token是公众号的全局唯一票据，公众号调用各接口时都需使用access_token。
	 * 正常情况下access_token有效期为7200秒，重复获取将导致上次获取的access_token失效。
	 * 由于获取access_token的api调用次数非常有限，建议开发者全局存储与更新access_token，
	 * 频繁刷新access_token会导致api调用受限，影响自身业务
	 */
	public static final Map<String, String> accessTokenMap = new HashMap<String, String>();
	public static final Map<String, Long> tokenCreateTime = new HashMap<String, Long>();
	/**
	 * 创建获取code链接
	 * @param appid 公众号appid
	 * @param url 回调函数url
	 * @param state 回调函数传回参数
	 * @param scope 链接授权作用域
	 */
	public synchronized static String getAccessToken(String appid, String appsecret) {
		if (isTokenTimeout(appid)) {
			refreshAccessToken(appid, appsecret);
		}
		return accessTokenMap.get(appid);
	}

	public static boolean isTokenTimeout(String appid) {
		long currentTime = System.currentTimeMillis();
		long lastGetTime = tokenCreateTime.get(appid) == null ? 0 : tokenCreateTime.get(appid) ;
		return (currentTime - lastGetTime) >= (Configure.TOKEN_TIMEOUT * 1000);
	}

	/**
	 * 刷新
	 * @param appid
	 * @param appsecret
	 * @return
	 */
	private synchronized static void refreshAccessToken(String appid, String appsecret) {
		try {
			String url = Configure.TOKEN_API.replace("APPID", Util.urlEnodeUTF8(appid)).replace("APPSECRET", Util.urlEnodeUTF8(appsecret));
			HttpGet request = new HttpGet(url);
			HttpResponse response = HttpClients.createDefault().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(response.getEntity());
				JSONObject jsonObject = new JSONObject(result);
				accessTokenMap.put(appid, (String) jsonObject.get("access_token"));
				tokenCreateTime.put(appid, System.currentTimeMillis());
			}
		} catch (Exception e) {
			logger.error("获取access_token失败", e);
		}
	}


	
}
